﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data;
using MvcApplication1.Models;
using System.Web;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
using System.Web.Security;
using System.Linq;

namespace MvcApplication1.Controllers
{
    public class ManageSessionCheckAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Session.IsNewSession && filterContext.HttpContext.Request.IsAuthenticated && filterContext.ActionDescriptor.ActionName!="UserManage")
            {
                //当请求来自admin时，若缓存失效，则自动跳转到admin主页，因为admin没有绑定的brand
                if (filterContext.HttpContext.User.IsInRole("admin") == true) filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "Controller", "Admin" }, { "Action", "Index" } });
                MembershipBrand brand = (filterContext.Controller as ManageController).MembershipService.GetBrandFromUserName((filterContext.Controller as Controller).User.Identity.Name);
                (filterContext.Controller as Controller).Session["manage"] = new Manage(brand);
            }
            base.OnActionExecuting(filterContext);
        }

    }

    //public class UploadifyAuthorize : ActionFilterAttribute
    //{
    //    HttpContextBase context = null;
    //    public override void OnActionExecuting(ActionExecutingContext filterContext)
    //    {
    //        context = filterContext.HttpContext;
    //        if (context.Request["RequireUploadifySessionSync"] != null)
    //            UploadifySessionSync();
    //        base.OnActionExecuting(filterContext);
    //    }

    //    protected void UploadifySessionSync()
    //    {
    //        try
    //        {
    //            string session_param_name = "SessionId";
    //            string session_cookie_name = "ASP.NET_SessionId";

    //            if (context.Request[session_param_name] != null)
    //                UploadifyUpdateCookie(session_cookie_name, context.Request.Form[session_param_name]);
    //        }
    //        catch { }

    //        try
    //        {
    //            string auth_param_name = "SecurityToken";
    //            string auth_cookie_name = FormsAuthentication.FormsCookieName;

    //            if (context.Request[auth_param_name] != null)
    //                UploadifyUpdateCookie(auth_cookie_name, context.Request.Form[auth_param_name]);
    //        }
    //        catch { }
    //    }

    //    private void UploadifyUpdateCookie(string cookie_name, string cookie_value)
    //    {
    //        HttpCookie cookie = context.Request.Cookies.Get(cookie_name);
    //        if (cookie == null)
    //            cookie = new HttpCookie(cookie_name);
    //        cookie.Value = cookie_value;
    //        context.Request.Cookies.Set(cookie);
    //    }
    //}

    [Authorize(Roles="admin, user",Order=2)]
    [ManageSessionCheck(Order=3)]
    public class ManageController : Controller
    {
        private Manage ma;
        public IMembershipService MembershipService { get { return new AccountMembershipService(); }  }

        protected override void Initialize(RequestContext requestContext)
        {
            //if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }
        //user main page
        public ActionResult UserManage(string sortorder,int? page,string itemname,string itemSN,string addtime,string linkaddr)
        {
            //if (Roles.GetRolesForUser().Contains("admin")) return RedirectToAction("Index", "Admin");
            MembershipBrand brand = MembershipService.GetBrandFromUserName(User.Identity.Name);
            if (Session["manage"] == null)
            {
                ma = new Manage(brand);
                Session["manage"] = ma;
            }
            else
                ma = (Manage)Session["manage"];
            ManagerSearch<DataView> ms = new DataViewManagerSearch(ma.ItemList, itemname, itemSN, addtime, linkaddr);
            DataView itemview = ms.SearchView;
            if (string.IsNullOrEmpty(sortorder) == false)
            {
                Sorter<DataView> sorter = new DataViewSorter();
                sorter.Sort(ref itemview, sortorder);
                ViewBag.sortorder = sortorder;
            }
            else
            {
                ViewBag.sortorder = "";
            }

            int pagenumber = page ?? 1;
            Pager<DataView> pager = new DataViewPager(ms.SearchView, pagenumber, 20);
            ViewBag.brandname = brand.brandName;
            ViewBag.pagecount = pager.PageCount;
            ViewBag.pagenumber = pagenumber;
            ViewBag.itemlist = pager.CurrentPage;
            ViewBag.itemname_search = itemname;
            ViewBag.itemSN_search = itemSN;
            ViewBag.addtime_search = addtime;
            ViewBag.linkaddr_search = linkaddr;
            
            return View();
        }

        //user edit page
        
        public ActionResult UserEditItem(string itemid)
        {
            Int64 itemID = Convert.ToInt64(itemid);
            ma = (Manage)Session["manage"];
            ma.ItemList.Sort="ID";
            int rowindex = ma.ItemList.Find(itemid);
            if (rowindex != -1)
                ViewBag.item = ma.ItemList[rowindex];
            else
                throw new Exception("the item doesn't exist in itemlist");
            ViewBag.itemkeyword = ma.GetItemKeyword(itemID);
            ViewBag.brandname = ma.brand.brandName;
            return View();
        }

        
        [HttpPost]
        public ActionResult UserEditItem(ItemEdit item,ReturnUrlParam reparam)
        {
            ma = (Manage)Session["manage"];
            ma.SaveItem(item);
            ((DataToSearch)HttpContext.Application["datatosearch"]).UpdateItem(item);
            string keywordstring = "";
            if (item.keywordlist != null)
            {
                ma.SaveKeyword(item);
                ((DataToSearch)HttpContext.Application["datatosearch"]).UpdateKeyword(item);
                KeywordItem[] keyworditems = item.GetKeywordList();
                if (keyworditems != null)
                {
                    foreach (KeywordItem keyword in keyworditems)
                    {
                        keywordstring = keywordstring + keyword.Keyword + " ";
                    }
                }
            }
            else
            {
                DataView keyworditems = ma.GetItemKeyword(item.GetItemID());
                foreach (DataRowView drv in keyworditems)
                {
                    keywordstring = keywordstring + (string)drv["keyword"] + " ";
                }
            }
            ViewBag.keywordstring = keywordstring;
            reparam.SetViewBag(ViewBag);
            return View("UserEditSuccess",item);
        }


        public ActionResult UserAddItem(ReturnUrlParam reparam)
        {
            reparam.SetViewBag(ViewBag);
            return View();
        }

        [HttpPost]
        public ActionResult UserAddItem(ItemEdit item, ReturnUrlParam reparam)
        {
            ma = (Manage)Session["manage"];
            ma.AddItem(item);
            ma.AddKeyword(item);
            ((DataToSearch)HttpContext.Application["datatosearch"]).AddItem(item);
            ViewBag.keywordstring = item.keywordlist;
            reparam.SetViewBag(ViewBag);
            return View("UserEditSuccess", item);
            //return Redirect("/Manage/UserManage");
        }
        
        public ActionResult UserDelItem(string itemidlist)
        {
            string[] strids = itemidlist.Split('|');
            Int64[] itemids = new Int64[strids.Length];
            for (int i=0;i<strids.Length;i++)
            {
                itemids[i] = Convert.ToInt64(strids[i]);
            }
            ((DataToSearch)HttpContext.Application["datatosearch"]).DelItem(itemids);
            ma = (Manage)Session["manage"];
            ma.DelItem(itemids);
            
            return RedirectToAction("UserManage");
        }

        [HttpPost]
        public string Upload(HttpPostedFileBase fileData,string itemid,string brandname,string oldimage)
        {
            if (FileIsWebFriendlyImage(fileData.InputStream) == false) return "Invaild file type";
            if (string.IsNullOrEmpty(oldimage)==false)
            {
                try
                {
                    System.IO.File.Delete(this.Server.MapPath("~/uploads/" + oldimage));
                }
                catch
                {
                    return "Retry";
                }
            }      
            Guid newid = Guid.NewGuid();
            string ext = System.IO.Path.GetExtension(fileData.FileName);
            string fileName = this.Server.MapPath("~/uploads/" + brandname+newid.ToString("N")+ext);
            fileData.SaveAs(fileName);

            return "ok|" + brandname + newid.ToString("N") + ext;
        }

        private bool FileIsWebFriendlyImage(Stream stream)
        {
            try
            {
                //Read an image from the stream...
                var i = Image.FromStream(stream);

                //Move the pointer back to the beginning of the stream
                stream.Seek(0, SeekOrigin.Begin);

                if (ImageFormat.Jpeg.Equals(i.RawFormat))
                    return true;
                return ImageFormat.Png.Equals(i.RawFormat)|| ImageFormat.Gif.Equals(i.RawFormat);
            }
            catch
            {
                return false;
            }
        }

        public ActionResult UserBrand()
        {
            ma = (Manage)Session["manage"];
            //ViewBag.brand = ma.brand;
            return View(ma.brand);
        }

        [HttpPost]
        public ActionResult UserBrand(string brandIntro,string Logo,string linkAddr,string brandtitle,string BrandKeywords)
        {
            if (string.IsNullOrEmpty(brandIntro) == true) brandIntro=""; 
            if(string.IsNullOrEmpty(linkAddr) == true) linkAddr="";
            if (string.IsNullOrEmpty(Logo) == true) Logo = "";
            if (string.IsNullOrEmpty(brandtitle) == true) brandtitle = "";
            ma = (Manage)Session["manage"];
            ma.brand.brandIntro = brandIntro;
            ma.brand.Logo = Logo;
            ma.brand.linkAddr = linkAddr;
            ma.brand.BrandTitle = brandtitle;
            if (string.Equals(BrandKeywords, "keyword=") == true) BrandKeywords = "";
            if (BrandKeywords.IndexOf('=') != -1)  //编辑关键字
            {
                string[] keyworditem = BrandKeywords.Split('&');
                BrandKeywords = "";
                for (int i = 0; i < keyworditem.Length; i++)
                {
                    string[] temp = keyworditem[i].Split('@');
                    BrandKeywords=BrandKeywords + temp[1]+" ";
                }
                BrandKeywords = BrandKeywords.Trim();
            }
            ma.brand.BrandKeywords = BrandKeywords;
            MembershipService.UpdateBrandInfo(ma.brand);
            ((DataToSearch)HttpContext.Application["datatosearch"]).UpdateBrand(ma.brand.brandName);
            ViewBag.state = "success";
            return View(ma.brand);

        }
    }
    
}